﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.ComponentModel;
using System.Windows.Threading;
using System.IO;
using TouchExplorer.Entities;

namespace TouchExplorer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static bool? _isInDesignMode;

        public delegate void BrowseFolderHandler(string folderPath);

        public event BrowseFolderHandler OnBrowseFolder;

        public ClipboardViewModel Clipboard { get; set; }

        public FavoritesViewModel Favorites { get; set; }

        public static App Current
        {
            get
            {
                return Application.Current as App;
            }
        }

        public App()
        {
            Favorites = FavoritesViewModel.Load();
        }

        /// <summary>
        /// Gets a value indicating whether the control is in design mode (running in Blend
        /// or Visual Studio).
        /// </summary>
        public static bool IsInDesignModeStatic
        {
            get
            {
                if (!_isInDesignMode.HasValue)
                {
#if SILVERLIGHT
            _isInDesignMode = DesignerProperties.IsInDesignTool;
#else
                    var prop = DesignerProperties.IsInDesignModeProperty;
                    _isInDesignMode
                        = (bool)DependencyPropertyDescriptor
                        .FromProperty(prop, typeof(FrameworkElement))
                        .Metadata.DefaultValue;
#endif
                }

                return _isInDesignMode.Value;
            }
        }

        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogError(e.Exception);
            MessageBox.Show("Ooops...");
            
        }

        void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogError(e.ExceptionObject as Exception);
            MessageBox.Show("Ooops...");
        }

        public static void LogError(Exception e)
        {
            if (e == null) return;
            LogText(e.ToString());
        }

        public static void LogText(String msg)
        {
            if (msg == null) return;
            using (var writer = new StreamWriter(string.Format("error_{0}.log", DateTime.Now.ToString("yyyyMMddHHmmss")), true))
            {
                writer.Write(msg + "\r\n");
            }
        }

        public void BrowseFolder(string p)
        {
            if (OnBrowseFolder != null) 
                OnBrowseFolder(p);
        }
    }
}
